package com.sky.service.impl;

import com.fasterxml.jackson.databind.JsonSerializable;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShopCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private ShopCartMapper shopCartMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void addshoppingcart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        Long currentId = BaseContext.getCurrentId();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shopCartMapper.list(shoppingCart);

        if(list!=null && list.size()>0){
            ShoppingCart shoppingCart1 = list.get(0);
            shoppingCart1.setNumber(shoppingCart1.getNumber()+1);
            shopCartMapper.updatenumber(shoppingCart1);
        }else{

            Long dishId = shoppingCart.getDishId();

            if(dishId !=null){
                Dish querybyid = dishMapper.querybyid(dishId);
                shoppingCart.setImage(querybyid.getImage());
                shoppingCart.setName(querybyid.getName());
                shoppingCart.setAmount(querybyid.getPrice());
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setNumber(1);
            }else{
                Long setmealId = shoppingCart.getSetmealId();
                SetmealVO querybyid = setmealMapper.querybyid(setmealId);
                shoppingCart.setImage(querybyid.getImage());
                shoppingCart.setName(querybyid.getName());
                shoppingCart.setAmount(querybyid.getPrice());
                shoppingCart.setCreateTime(LocalDateTime.now());
                shoppingCart.setNumber(1);

            }

            shopCartMapper.insert(shoppingCart);

        }
    }


    @Override
    public List<ShoppingCart> showcart() {
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = ShoppingCart.builder()
                        .userId(currentId)
                                .build();
        return  shopCartMapper.list(shoppingCart);
    }

    @Override
    public void clear() {
        Long currentId = BaseContext.getCurrentId();
        shopCartMapper.clear(currentId);
    }
}
